package com.zhangmeng.tools.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.zhangmeng.tools.nettyClient.NettyClient;
import com.zhangmeng.tools.utils.AlertUtils;
import com.zhangmeng.tools.utils.HttpUtils;
import com.zhangmeng.tools.utils.ImagePath;
import com.zhangmeng.tools.utils.ResourcesUtils;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Paint;
import javafx.scene.text.Font;
import javafx.util.Callback;
import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ChatAppImplController {

    public enum Type{
        ws("ws"),
        wss("wss")
        ;

        Type(String name) {
            this.name = name;
        }

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }


    public static String HOST = "http://localhost:8083";

    public static int netty_port = 8888;
    public static String netty_host = "localhost";

    @FXML
    public Button file_button;

    @FXML
    public ListView<ChatFriend> listView;

    @FXML
    public TextArea content;

    private ObservableList<ChatFriend> chatFriendList = FXCollections.observableArrayList();

    public static final String color_cell = "#f4f4f4";

    private WebSocketClient webSocketClient;

    @FXML
    public void initialize() {

        file_button.setText(null);
        ImageView iv = new ImageView(new Image(ImagePath.path(ImagePath.ImagePathType.IMAGE_FILE)));
        iv.setPreserveRatio(true);
        iv.setFitWidth(18);
        file_button.setGraphic(iv);
        init_list_view();
        listView.setItems(chatFriendList);

        content.setOnKeyPressed(event -> {
            if (event.getCode() == KeyCode.ENTER) {
                sendMsg();
                content.clear();
            }

        });
        file_button.setOnAction(event -> getChatFriendList());
        init_netty_client();
    }

    public void init_netty_client(){
        if (webSocketClient == null) {
            webSocketClient(ChatAppImplController.Type.ws, netty_host, netty_port, "/websocket", "userId=1&source=pc");
        }
    }

    public void sendMsg(){
        if (content.getText().isEmpty()){
            AlertUtils.alert_warning("请输入文本在发送!");
            return;
        }
        webSocketClient.send(content.getText());
    }

    public void webSocketClient(ChatAppImplController.Type type, String socket_address, int socket_port, String path , String params) {
        try {
            webSocketClient = new WebSocketClient(new URI(type.name + "://" + socket_address + ":" + socket_port + path + "?" + params), new Draft_6455()) {
                //连接服务端时触发
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    log.info("websocket客户端和服务器连接成功");
                }
                //收到服务端消息时触发
                @Override
                public void onMessage(String message) {
                    log.info("websocket客户端收到消息={}", message);
                }
                //和服务端断开连接时触发
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.info("websocket客户端退出连接");
                }
                //连接异常时触发
                @Override
                public void onError(Exception ex) {
                    log.info("websocket客户端和服务器连接发生错误={}", ex.getMessage());
                }
            };
            webSocketClient.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void init_list_view(){
        listView.setCellFactory(new Callback<>() {
            private int position;
            @Override
            public ListCell<ChatFriend> call(ListView<ChatFriend> listView) {
                Label label = new Label();
                label.setPrefWidth(200);
                ListCell<ChatFriend> listCell = new ListCell<>() {
                    @Override
                    protected void updateItem(ChatFriend chatFriend, boolean b) {
                        super.updateItem(chatFriend, b);
                        if (!b) {
                            HBox hBox = new HBox(25);
                            hBox.setAlignment(Pos.CENTER);
                            label.setText(chatFriend.getFriend_name());
                            label.setTextFill(Paint.valueOf("#000000"));
                            label.setFont(Font.font(20));
                            hBox.getChildren().add(label);
                            this.setGraphic(hBox);
                        }
                        this.setStyle("-fx-background-color: " + color_cell);
                    }
                };

                listCell.hoverProperty().addListener((observableValue, aBoolean, t1) -> {
                    if (t1 && !label.getText().equals("")) {
                        position = listView.getItems().indexOf(label.getText());
                        label.setFont(new Font(16));
                        listView.getFocusModel().focus(position);
                        listCell.setStyle("-fx-background-color: #369e7d");
                    } else {
                        label.setPrefHeight(20);
                        label.setFont(new Font(13));
                        listCell.setStyle("-fx-background-color: " + color_cell);
                    }
                });

                return listCell;
            }
        });
    }

    public void getChatFriendList() {
        Map<String, Object> query = new HashMap<>();
        query.put("id", "1");
        String json = HttpUtils.get_request(HOST + "/chatFriend/list", query);
        log.info(json);

        List<ChatFriend> list = JSON.parseArray(json, ChatFriend.class);
        if (!list.isEmpty()) {
            chatFriendList.setAll(list);
        }
    }

    @Data
    public static class ChatFriend {

        public ChatFriend(String friend_id, String friend_name, String self_id, String self_name) {
            this.friend_id = friend_id;
            this.friend_name = friend_name;
            this.self_id = self_id;
            this.self_name = self_name;
        }

        private String friend_id;
        private String friend_name;
        private String self_id;
        private String self_name;
    }
}
